import { NextRequest, NextResponse } from 'next/server';

// get接口,访问http://localhost:3001/api/unit1/test-post
export async function POST(request: NextRequest) {
  const { url } = request;

  // 用request.json()和request.formData()这种异步的记得做错误处理,因为只有一没有对上匹配的数据格式就报错
  // 获取请求正文, 获取formData同理
  let body = {};
  try {
    body = await request.json();
    console.log('========body========', body);
  } catch (error) {
    console.log('========error========', error);
  }

  // 获取请求的params URL 参数 对象格式
  const searchParams = Object.fromEntries(request.nextUrl.searchParams);
  console.log('======searchParams======', searchParams);

  // 获取请求的header信息 对象格式
  const headers = Object.fromEntries(request.headers);
  console.log('===========headers===========', headers);

  // 获取cookie信息 格式[ { name: 'name', value: 'test1' } ]
  const cookies = request.cookies.getAll();
  console.log('===========cookies===========', cookies);

  return NextResponse.json(
    {
      name: 'test-post',
      url,
      reqbody: body,
      reqsearchParams: searchParams,
      reqheaders: headers,
    },
    // 设置标头等
    {
      headers: {
        // status: '200',
        // 'Set-Cookie': 'name=test-post',
      },
    }
  );
}
